﻿using Microsoft.Xna.Framework;
using SolarWinds.Cameras;
using Microsoft.Xna.Framework.Graphics;

namespace SolarWinds.Helpers
{
    class PickingHelper
    {
        /// <summary>
        /// Gets 3D position of 2D mouse pointer, weher Y = 0 is on the XZ-plane    
        /// </summary>
        /// <param name="camera"></param>
        /// <param name="mousePosition"></param>
        /// <returns></returns>
        public static Vector3 GetPickedPosition(Camera camera, Vector2 mousePosition)
        {
            // create 2 positions in screenspace using the cursor position. 0 is as
            // close as possible to the camera, 10 is as far away as possible
            var nearSource = new Vector3(mousePosition, 0f);
            var farSource = new Vector3(mousePosition, camera.NearPlane);


            // find the two screen space positions in world space
            Viewport viewport = SolarWindsGame.GraphicsDeviceManager.GraphicsDevice.Viewport;
            Vector3 nearPoint = viewport.Unproject(nearSource, camera.Projection,
                                                   camera.View, Matrix.Identity);
            Vector3 farPoint = viewport.Unproject(farSource, camera.Projection,
                                                  camera.View, Matrix.Identity);

            // normalized direction vector from nearPoint to farPoint
            Vector3 direction = farPoint - nearPoint;
            direction.Normalize();

            // create a ray using nearPoint as the source
            var ray = new Ray(nearPoint, direction);

            // define the Y=0 plane
            var normal = new Vector3(0f, 1f, 0f);
            var plane = new Plane(normal, 0f);

            // calcuate distance of plane intersection point from ray origin
            float? t = ray.Intersects(plane);

            // calculate the picked position on the y = 0 plane
            Vector3 pickedPosition = (t == null) ? Vector3.Zero : nearPoint + direction * (float)t;

            return pickedPosition;
        }
    }
}
